package io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class CSVParser {

	private static final String CSV_SEPARATOR = ",";
	
	private String csvFilePath = null;
	private BufferedReader br = null;
	
	/**
	 * Opens a CSV file to be read. 
	 * @param path Path of the file to be opened.
	 * @throws FileNotFoundException If the file is not found.
	 */
	public CSVParser(String path) throws FileNotFoundException {
		if(br != null) {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		csvFilePath = path;
		br = new BufferedReader(new FileReader(csvFilePath));
		
	}
	
	/**
	 * Reads a line from the currently opened CSV file.
	 * @return A List of Strings containing the comma-separated values from the line, or null if the end of the stream has been reached.  
	 */
	public List<String> nextLine() {
		if(br == null)
			return null;
		
		String line = null;
		boolean comment = true;
		try {
			while(comment) {
				comment = false;
				line = br.readLine();
				
				//Ignore comments.
				if(line != null)
					if(line.startsWith("#"))
						comment = true;
			}
				
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(line != null)
			return Arrays.asList(line.split(CSV_SEPARATOR));
		else
			return null;
	}
}
